import 'dart:convert';
import 'dart:math';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:get_storage/get_storage.dart';
import 'package:laos_mall/common/utils/http_util.dart';
import 'package:laos_mall/common/utils/num_util.dart';
import 'package:laos_mall/common/widght/toast/showtoast.dart';
import 'package:laos_mall/models/home/home_model.dart';
import 'package:laos_mall/models/home/product_detail_model.dart';
import 'package:laos_mall/pages/main/shopping_cart/logic.dart';
import 'package:laos_mall/user_data.dart';

import '../product_detail/logic.dart';

class SkuLogic extends GetxController {
  SkuLogic({this.productId,this.skuId});
  var price = "0.0".obs;
  var unitPrice = 0.0;
  var skuNum = 1.obs;
  var buyNum = 1.obs;
  var selIndex = 0;
  double skuMaxWidth = 200;
  bool isFirst = true;
  var thumbUrl = Rx<String?>(null);
  ///详情的
  ProductDetailModel? model;
  ///首页的
  Products? homeModel;
  int? skuId;
  int? productId;
  var skuModel = Rx<Sku_list?>(null);
  @override
  void onInit()async {

    try {
      model = Get
          .find<ProductDetailLogic>()
          .model;
      thumbUrl.value = model?.item?.pic_thumb;
      skuId = Get
          .find<ProductDetailLogic>()
          .skuId;
    }catch(_){

      var res = await HttpUtil.restApi.productDetail({"skuId":skuId,"id":productId});
      model = res.data;
      thumbUrl.value = model?.item?.pic_thumb;
      // model = ProductDetailModel.fromJson(srcJson);
    }
    getDefaultSelect();
    super.onInit();
  }

  getDefaultSelect(){
    skuModel.value = model?.sku_list?.firstWhereOrNull((element) => element.sku_id == skuId);
    skuModel.value ??= model?.sku_list?.first;
    price.value = NumUtils.parse(skuModel.value?.sku_price);
  }

  setSkuOfValue(int index,String value){
    ///深拷贝
    var changeModel = model?.sku_list?.firstWhereOrNull((element) => element.sku_id == skuModel.value!.sku_id);
    var modelMap = changeModel?.toJson();
    modelMap!["sku_data"] = changeModel!.sku_data.map((e) => e.toJson()).toList();
    var newItem = Sku_list.fromJson(modelMap);
    newItem.sku_data[index].value = value;
    if(model?.sku_list != null) {
      for (var element in model!.sku_list!) {
        if (areSkuListsEqual(element.sku_data, newItem.sku_data)) {
          skuModel.value = element;
          update();
          break;
        }
      }
    }

  }

  bool areSkuListsEqual(List<Sku_data> list1, List<Sku_data> list2) {
    if (list1.length != list2.length) return false;

    for (int i = 0; i < list1.length; i++) {
      if (list1[i].value != list2[i].value) {
        return false;
      }
    }
    // print("list1:  ${list1.last.name} = ${list1.last.value}, ${list1.first.name} = ${list1.first.value}  list2:  ${list2.last.name} = ${list1.last.value},  ${list2.first.name} = ${list2.first.value}");
    return true;
  }

  double scaleMaxWith() {
    return 100.0;
  }



  Size getTextSize(String text, TextStyle style) {
    final textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      textDirection: TextDirection.ltr,
    )..layout();
    return textPainter.size;
  }

  addOrder()async{
    UserData().loginJudge(callback: ()async{
      var param = {
        "id":model?.item?.product_id,
        "sku_id":skuModel.value?.sku_id,
        "number":buyNum.value,
        //todo: 不清楚是啥
        "is_quick":0
      };
      var res = await HttpUtil.restApi.addToCart(param);
      if(res.code == 0){
        showToast("hint_add_cart_success".tr,type: ToastType.success);
        UserData().cartNum += 1;
        final logic = Get.find<ShoppingCartLogic>();
        logic.onRefresh();
      }else{
        showToast("hint_add_cart_fail".tr,type: ToastType.error);
      }

    });
  }
}
